<template>
  <div class="detection-page">
    <div class="card-stack">
      <el-card class="card-block breadcrumb-card">
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>质量管理</el-breadcrumb-item>
          <el-breadcrumb-item>检测管理</el-breadcrumb-item>
          <el-breadcrumb-item>检测项目</el-breadcrumb-item>
        </el-breadcrumb>
      </el-card>

      <el-card class="card-block filter-card">
        <el-form :inline="true" :model="queryForm" label-width="auto" class="filter-form">
          <el-form-item label="项目编号">
            <el-input v-model="queryForm.testitemcard" placeholder="请输入检测项目编号" clearable />
          </el-form-item>
          <el-form-item label="项目名称">
            <el-input v-model="queryForm.testitemname" placeholder="请输入检测项目名称" clearable />
          </el-form-item>
          <el-form-item label="检测类型">
            <el-select v-model="queryForm.detectiontypeid" placeholder="请选择检测类型" clearable>
              <el-option
                v-for="item in detectionTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检测工具">
            <el-select v-model="queryForm.detectiontoolid" placeholder="请选择检测工具" clearable>
              <el-option
                v-for="item in detectionToolOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryForm.testitemstate" placeholder="请选择状态" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card class="card-block table-card">
        <div class="table-toolbar">
          <div>
            <el-button type="primary" @click="startCreate">新增</el-button>
            <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">删除</el-button>
          </div>
          <div class="table-total">共 {{ pagination.totalCount }} 条</div>
        </div>
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          :loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="index" label="序号" width="70" />
          <el-table-column prop="testitemname" label="检测项目名称" min-width="150" />
          <el-table-column prop="testitemcard" label="检测项目编码" min-width="140" />
          <el-table-column prop="detectiontypename" label="检测类型" min-width="120" />
          <el-table-column prop="detectiontoolname" label="检测工具" min-width="120" />
          <el-table-column label="状态" width="110">
            <template #default="{ row }">
              <el-tag :type="row.testitemstate === '启用' ? 'success' : 'info'">{{ row.testitemstate }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="testitemdes" label="备注" min-width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="startEdit(row)">编辑</el-button>
              <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :total="pagination.totalCount"
            :page-sizes="[10, 20, 30, 50]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <el-card class="card-block form-card">
        <div class="form-card__header">
          <div class="title">{{ formMode === "create" ? "新增" : "编辑" }}检测项目</div>
          <el-button type="info" text size="small" @click="resetForm">清空</el-button>
        </div>
        <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px" class="side-form">
          <el-form-item label="项目编码" prop="testitemcard">
            <el-input v-model="formModel.testitemcard" :disabled="formModel.useSystemCode" placeholder="请输入项目编码">
              <template #suffix>
                <span class="system-flag">
                  <span>系统编号</span>
                  <el-switch
                    v-model="formModel.useSystemCode"
                    size="small"
                    inline-prompt
                    active-text="是"
                    inactive-text="否"
                    @change="handleSystemCodeChange"
                  />
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="项目名称" prop="testitemname">
            <el-input v-model="formModel.testitemname" placeholder="请输入项目名称" />
          </el-form-item>
          <el-form-item label="检测类型" prop="detectiontypeid">
            <el-select v-model="formModel.detectiontypeid" placeholder="请选择检测类型">
              <el-option
                v-for="item in detectionTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检测工具" prop="detectiontoolid">
            <el-select v-model="formModel.detectiontoolid" placeholder="请选择检测工具">
              <el-option
                v-for="item in detectionToolOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="testitemstate">
            <el-radio-group v-model="formModel.testitemstate">
              <el-radio-button label="启用" />
              <el-radio-button label="禁用" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="testitemdes">
            <el-input v-model="formModel.testitemdes" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <div class="form-card__footer">
          <el-button @click="resetForm">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight } from "@element-plus/icons-vue";
import { computed, onMounted, reactive, ref } from "vue";
import https from "@/Http/http";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";

type ApiEnum = -1 | 0 | 1;

interface ApiPageingResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResultResponse<T> {
  code: ApiEnum;
  msg: string;
  data: T;
}

interface TestItemDTO {
  id: number;
  testitemcard: string;
  testitemname: string;
  detectiontypeid: number;
  detectiontypename: string;
  detectiontoolid: number;
  detectiontoolname: string;
  testitemstate: string;
  testitemdes: string;
}

interface SelectOption {
  label: string;
  value: number;
}

interface DropdownSources {
  types: DetectionTypeDTO[];
  tools: DetectionToolDTO[];
}

interface DetectionTypeDTO {
  id: number;
  detectiontypename: string;
}

interface DetectionToolDTO {
  id: number;
  detectiontoolname: string;
}

interface TestItemTableRow extends TestItemDTO {
  index: number;
}

const loading = ref(false);
const tableData = ref<TestItemTableRow[]>([]);
const multipleSelection = ref<TestItemTableRow[]>([]);

const dropdownSources = reactive<DropdownSources>({
  types: [],
  tools: [],
});

const detectionTypeOptions = computed<SelectOption[]>(() =>
  dropdownSources.types.map((item) => ({
    label: item.detectiontypename,
    value: item.id,
  })),
);

const detectionToolOptions = computed<SelectOption[]>(() =>
  dropdownSources.tools.map((item) => ({
    label: item.detectiontoolname,
    value: item.id,
  })),
);

const statusOptions = [
  { label: "启用", value: "启用" },
  { label: "禁用", value: "禁用" },
];

const queryForm = reactive({
  testitemcard: "",
  testitemname: "",
  detectiontypeid: undefined as number | undefined,
  detectiontoolid: undefined as number | undefined,
  testitemstate: "",
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

const formMode = ref<"create" | "edit">("create");
const formRef = ref<FormInstance>();
const formModel = reactive({
  id: undefined as number | undefined,
  testitemcard: "",
  testitemname: "",
  detectiontypeid: undefined as number | undefined,
  detectiontoolid: undefined as number | undefined,
  testitemstate: "启用",
  testitemdes: "",
  useSystemCode: true,
});

const rules: FormRules = {
  testitemcard: [{ required: true, message: "请输入检测项目编码", trigger: "blur" }],
  testitemname: [{ required: true, message: "请输入检测项目名称", trigger: "blur" }],
  detectiontypeid: [{ required: true, message: "请选择检测类型", trigger: "change" }],
  detectiontoolid: [{ required: true, message: "请选择检测工具", trigger: "change" }],
};

const generateCode = () => {
  const now = new Date();
  return `JYXM${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, "0")}${now
    .getDate()
    .toString()
    .padStart(2, "0")}${now.getHours().toString().padStart(2, "0")}${now.getMinutes().toString().padStart(2, "0")}${now
    .getSeconds()
    .toString()
    .padStart(2, "0")}`;
};

const handleSystemCodeChange = () => {
  if (formModel.useSystemCode) {
    formModel.testitemcard = generateCode();
  } else {
    formModel.testitemcard = "";
  }
};

const fetchDropdownOptions = async () => {
  try {
    const [typeRes, toolRes] = await Promise.all([
      https.Reads.get<ApiPageingResponse<DetectionTypeDTO>>("/Detection/DetectionTypeList", {
        params: { pageindex: 1, pagesize: 999 },
      }),
      https.Reads.get<ApiPageingResponse<DetectionToolDTO>>("/Detection/DetectionToolList", {
        params: { pageindex: 1, pagesize: 999 },
      }),
    ]);
    dropdownSources.types = typeRes.data.data ?? [];
    dropdownSources.tools = toolRes.data.data ?? [];
  } catch (error) {
    console.error(error);
    ElMessage.error("获取下拉数据失败");
  }
};

const fetchTableData = async () => {
  loading.value = true;
  try {
    const { data } = await https.Reads.get<ApiPageingResponse<TestItemDTO>>("/Detection/TestItemList", {
      params: {
        pagesize: pagination.pageSize,
        pageindex: pagination.pageIndex,
        testitemcard: queryForm.testitemcard,
        testitemname: queryForm.testitemname,
        detectiontypeid: queryForm.detectiontypeid,
        detectiontoolid: queryForm.detectiontoolid,
        testitemstate: queryForm.testitemstate,
      },
    });
    if (data.code !== 1) {
      throw new Error(data.msg || "查询失败");
    }
    pagination.totalCount = data.totalCount || 0;
    tableData.value = (data.data || []).map((item, index) => ({
      ...item,
      index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1,
    }));
  } catch (error: any) {
    console.error(error);
    ElMessage.error(error.message || "获取检测项目失败");
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.testitemcard = "";
  queryForm.testitemname = "";
  queryForm.detectiontypeid = undefined;
  queryForm.detectiontoolid = undefined;
  queryForm.testitemstate = "";
  handleQuery();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchTableData();
};

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page;
  fetchTableData();
};

const handleSelectionChange = (rows: TestItemTableRow[]) => {
  multipleSelection.value = rows;
};

const resetForm = () => {
  formRef.value?.resetFields();
  formMode.value = "create";
  formModel.id = undefined;
  formModel.useSystemCode = true;
  formModel.testitemstate = "启用";
  formModel.detectiontypeid = undefined;
  formModel.detectiontoolid = undefined;
  formModel.testitemdes = "";
  handleSystemCodeChange();
};

const startCreate = () => {
  formMode.value = "create";
  resetForm();
};

const startEdit = (row: TestItemDTO) => {
  formMode.value = "edit";
  formModel.id = row.id;
  formModel.testitemcard = row.testitemcard;
  formModel.testitemname = row.testitemname;
  formModel.detectiontypeid = row.detectiontypeid;
  formModel.detectiontoolid = row.detectiontoolid;
  formModel.testitemstate = row.testitemstate;
  formModel.testitemdes = row.testitemdes;
  formModel.useSystemCode = false;
};

const buildPayload = () => ({
  id: formModel.id,
  testitemcard: formModel.testitemcard,
  testitemname: formModel.testitemname,
  detectiontypeid: formModel.detectiontypeid,
  detectiontoolid: formModel.detectiontoolid,
  testitemstate: formModel.testitemstate,
  testitemdes: formModel.testitemdes,
});

const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    try {
      const payload = buildPayload();
      const response =
        formMode.value === "create"
          ? await https.Writes.post<ApiResultResponse<number>>("/Detection/TestItemAdd", payload)
          : await https.Writes.put<ApiResultResponse<number>>("/Detection/TestItemUpdate", payload);
      if (response.data.code !== 1) {
        throw new Error(response.data.msg || "保存失败");
      }
      ElMessage.success("保存成功");
      resetForm();
      fetchTableData();
    } catch (error: any) {
      console.error(error);
      ElMessage.error(error.message || "保存失败");
    }
  });
};

const handleDelete = (row: TestItemTableRow) => {
  ElMessageBox.confirm(`确认删除检测项目【${row.testitemname}】吗？`, "提示", { type: "warning" })
    .then(async () => {
      try {
        const res = await https.Writes.delete<ApiResultResponse<number>>("/Detection/TestItemDel", {
          params: { id: row.id },
        });
        if (res.data.code !== 1) {
          throw new Error(res.data.msg || "删除失败");
        }
        ElMessage.success("删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "删除失败");
      }
    })
    .catch(() => {});
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) return;
  ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 条数据吗？`, "提示", { type: "warning" })
    .then(async () => {
      try {
        await Promise.all(
          multipleSelection.value.map((item) =>
            https.Writes.delete<ApiResultResponse<number>>("/Detection/TestItemDel", {
              params: { id: item.id },
            }),
          ),
        );
        ElMessage.success("批量删除成功");
        fetchTableData();
      } catch (error: any) {
        console.error(error);
        ElMessage.error(error.message || "批量删除失败");
      }
    })
    .catch(() => {});
};

onMounted(async () => {
  handleSystemCodeChange();
  await fetchDropdownOptions();
  fetchTableData();
});
</script>

<style scoped>
.detection-page {
  min-height: calc(100vh - 60px);
  padding: 16px;
  background: linear-gradient(135deg, #f0f4ff 0%, #fef5f6 45%, #fdf8ff 100%);
}

.card-stack {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.card-block {
  width: 100%;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.88), rgba(242, 248, 255, 0.82));
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 10px 30px rgba(15, 36, 70, 0.08);
  border-radius: 12px;
  backdrop-filter: blur(12px);
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.table-total {
  color: #909399;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}

.form-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.form-card__header .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.system-flag {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #909399;
}

.form-card__footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 16px;
}
</style>




